﻿#include "stdafx.h"
#include "HttpServer.h"
#include <QHttpServer>
#include <QJsonDocument>
#include <QJsonObject>

HttpServer::HttpServer(QObject* parent)
	:QObject(parent)
{

}

static QString createUrls()
{
	QJsonObject jsObj;
	jsObj.insert("update", "http://32749wz98ph3.vicp.fun/update");
	jsObj.insert("advertisement", "http://32749wz98ph3.vicp.fun/advertisement");
	return QJsonDocument(jsObj).toJson();
}

void HttpServer::start(int port)
{
	if (m_server == nullptr)
	{
		m_server = new QHttpServer(this);
		m_server->route("/", []() {
			return QString::fromUtf8("<head><meta http-equiv=\"Content-Type\" content=\"text//html;charset=utf-8\"></head>http服务测试？");
		});
		m_server->route("/urls", []() {
			return createUrls();
		});
		m_server->route("/page/<arg>/<arg>", [](int pageNum, int mm) {
			return QString("%1/%2").arg(pageNum).arg(mm);
		});

		if (!m_server->listen(QHostAddress::Any, port))
		{
			Q_ASSERT(false);
			qWarning() << "Failed to start server";
		}
	}
}

void HttpServer::stop()
{
	if(m_server)
	{
		m_server->deleteLater();
		m_server = nullptr;
	}
}
